package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import com.itheima.domain.*;
import com.itheima.service.AdminService;
import com.itheima.service.UserService;
import com.itheima.utils.ResourceNotFoundException;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserService userService;

    @GetMapping("/dashboard")
    public String dashboard(HttpSession session, Model model) {
        // 检查管理员登录状态
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            session.setAttribute("error", "请先登录账号");
            return "redirect:/login";
        }

        // 获取统计数据
        AdminStatsVO stats = adminService.getAdminStats();

        // 获取最近活动
        List<AdminActivityVO> activities = adminService.getRecentActivities(10);

        // 添加到模型
        model.addAttribute("admin", admin);
        model.addAttribute("stats", stats);
        model.addAttribute("activities", activities);
        model.addAttribute("activeTab", "dashboard");

        return "/dashboard";
    }

    @GetMapping("/chartData")
    @ResponseBody
    public Map<String, Object> getChartData(@RequestParam String type) {
        Map<String, Object> result = new HashMap<>();

        switch (type) {
            case "week":
                result.put("labels", Arrays.asList("周一", "周二", "周三", "周四", "周五", "周六", "周日"));
                result.put("data", adminService.getWeeklySalesData());
                break;

            case "month":
                result.put("labels", adminService.getMonthlyLabels());
                result.put("data", adminService.getMonthlySalesData());
                break;

            case "category":
                result.put("labels", adminService.getCategoryNames());
                result.put("data", adminService.getCategorySalesData());
                break;

            default:
                throw new IllegalArgumentException("不支持的图表类型: " + type);
        }

        return result;
    }

    @GetMapping("/userManage")
    public String userManage(
            HttpSession session,
            Model model,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        // 检查管理员登录状态
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            session.setAttribute("error", "请先登录账号");
            return "redirect:/login";
        }

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 获取用户列表
        List<User> userList;
        int totalUsers;
        if (StringUtils.isNotBlank(keyword)) {
            userList = adminService.searchUsersWithPagination(keyword, offset, pageSize);
            totalUsers = adminService.countUsersByKeyword(keyword);
        } else {
            userList = adminService.getAllUsersWithPagination(offset, pageSize);
            totalUsers = adminService.countAllUsers();
        }

        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalUsers / pageSize);

        model.addAttribute("admin", admin);
        model.addAttribute("users", userList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("keyword", keyword);
        model.addAttribute("activeTab", "user");
        return "/userManagement";
    }

    @GetMapping("/productManage")
    public String productManage(
            HttpSession session,
            Model model,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "sort", defaultValue = "newest") String sort,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        // 检查管理员登录状态
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            session.setAttribute("error", "请先登录账号");
            return "redirect:/login";
        }

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 获取商品列表和总数
        List<Product> productList = adminService.searchProductsWithPagination(keyword, categoryId, status, sort, offset, pageSize);
        int totalProducts = adminService.countProducts(keyword, categoryId, status);

        // 获取所有分类
        List<Category> categories = adminService.getAllCategories();

        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalProducts / pageSize);

        model.addAttribute("admin", admin);
        model.addAttribute("products", productList);
        model.addAttribute("categories", categories);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("keyword", keyword);
        model.addAttribute("categoryId", categoryId);
        model.addAttribute("status", status);
        model.addAttribute("sort", sort);
        model.addAttribute("activeTab", "product");
        return "/productManagement";
    }

    @GetMapping("/orderManege")
    public String orderManage(
            HttpSession session,
            Model model,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "timeRange", defaultValue = "all") String timeRange,
            @RequestParam(value = "sort", defaultValue = "newest") String sort,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {

        // 检查管理员登录状态
        Admin admin = (Admin) session.getAttribute("admin");
        if (admin == null) {
            session.setAttribute("error", "请先登录账号");
            return "redirect:/login";
        }

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 获取订单列表和总数
        List<Order> orderList = adminService.searchOrdersWithPagination(keyword, status, timeRange, sort, offset, pageSize);
        int totalOrders = adminService.countOrders(keyword, status, timeRange);

        // 获取所有用户和商品(用于显示关联信息)
        List<User> userList = adminService.getAllUsers();
        List<Product> productList = adminService.getAllProducts();

        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalOrders / pageSize);

        model.addAttribute("admin", admin);
        model.addAttribute("orders", orderList);
        model.addAttribute("users", userList);
        model.addAttribute("products", productList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("keyword", keyword);
        model.addAttribute("status", status);
        model.addAttribute("timeRange", timeRange);
        model.addAttribute("sort", sort);
        model.addAttribute("activeTab", "order");
        return "/orderManagement";
    }

    @GetMapping("/user/export")
    public void exportUsers(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            HttpServletResponse response) throws IOException {

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户数据", "UTF-8") + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 获取数据
        List<User> userList;
        if (StringUtils.isNotBlank(keyword)) {
            userList = adminService.searchUsersWithPagination(keyword, offset, pageSize);
        } else {
            userList = adminService.getAllUsersWithPagination(offset, pageSize);
        }

        // 导出Excel
        EasyExcel.write(response.getOutputStream(), User.class)
                .registerWriteHandler(new AbstractColumnWidthStyleStrategy() {
                    @Override
                    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
                        Sheet sheet = writeSheetHolder.getSheet();
                        // 设置所有列的默认宽度（单位：字符）
                        sheet.setDefaultColumnWidth(20);
                    }
                })
                .sheet("用户数据")
                .doWrite(userList);
    }

    @GetMapping("/product/export")
    public void exportProducts(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "categoryId", required = false) Integer categoryId,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "sort", defaultValue = "newest") String sort,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            HttpServletResponse response) throws IOException {

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("商品数据", "UTF-8") + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 获取数据
        List<Product> productList = adminService.searchProductsWithPagination(
                keyword, categoryId, status, sort, offset, pageSize);

        // 导出Excel
        EasyExcel.write(response.getOutputStream(), Product.class)
                .registerWriteHandler(new AbstractColumnWidthStyleStrategy() {
                    @Override
                    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
                        Sheet sheet = writeSheetHolder.getSheet();
                        // 设置所有列的默认宽度（单位：字符）
                        sheet.setDefaultColumnWidth(20);
                    }
                })
                .sheet("商品数据")
                .doWrite(productList);
    }

    @GetMapping("/order/export")
    public void exportOrders(
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "timeRange", defaultValue = "all") String timeRange,
            @RequestParam(value = "sort", defaultValue = "newest") String sort,
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            HttpServletResponse response) throws IOException {

        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("订单数据", "UTF-8") + ".xlsx";
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        // 计算偏移量
        int offset = (page - 1) * pageSize;

        // 获取数据
        List<Order> orderList = adminService.searchOrdersWithPagination(
                keyword, status, timeRange, sort, offset, pageSize);

        // 获取关联数据
        List<User> users = adminService.getAllUsers();
        List<Product> products = adminService.getAllProducts();

        // 创建导出DTO列表
        List<OrderExportDTO> exportList = orderList.stream().map(order -> {
            OrderExportDTO dto = new OrderExportDTO();
            // 复制订单基础信息
            BeanUtils.copyProperties(order, dto);

            // 设置买家信息
            users.stream()
                    .filter(user -> user.getUserId().equals(order.getBuyerId()))
                    .findFirst()
                    .ifPresent(user -> {
                        dto.setBuyerName(user.getUsername());
                        dto.setBuyerPhone(user.getPhone());
                    });

            // 设置卖家信息
            users.stream()
                    .filter(user -> user.getUserId().equals(order.getSellerId()))
                    .findFirst()
                    .ifPresent(user -> {
                        dto.setSellerName(user.getUsername());
                        dto.setSellerPhone(user.getPhone());
                    });

            // 设置商品信息
            products.stream()
                    .filter(product -> product.getProductId().equals(order.getProductId()))
                    .findFirst()
                    .ifPresent(product -> {
                        dto.setProductName(product.getTitle());
                        dto.setProductCategory(product.getCategoryId());
                    });

            return dto;
        }).collect(Collectors.toList());

        // 导出Excel
        EasyExcel.write(response.getOutputStream(), OrderExportDTO.class)
                .registerWriteHandler(new AbstractColumnWidthStyleStrategy() {
                    @Override
                    protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
                        Sheet sheet = writeSheetHolder.getSheet();
                        // 设置所有列的默认宽度（单位：字符）
                        sheet.setDefaultColumnWidth(20);
                    }
                })
                .sheet("订单数据")
                .doWrite(exportList);
    }

    // 用户详情查看
    @GetMapping("/detail")
    public String getUserDetail(@RequestParam("id") Integer userId, Model model) {
        User user = adminService.getUserById(userId);
        if (user == null) {
            throw new ResourceNotFoundException("用户不存在");
        }
        model.addAttribute("user", user);
        return "/userDetail"; // 返回用户详情视图
    }

    // 商品详情查看
    @GetMapping("/product/detail")
    public String getProductDetail(@RequestParam("id") Integer productId, Model model) {
        Product product = adminService.getProductById(productId);
        List<Category> categories = adminService.getAllCategories();
        User seller = adminService.getUserById(product.getUserId());
        if (product == null) {
            throw new ResourceNotFoundException("商品不存在");
        } else if (categories == null) {
            throw new ResourceNotFoundException("分类不存在");
        } else if (seller == null) {
            throw new ResourceNotFoundException("卖家不存在");
        }
        model.addAttribute("product", product);
        model.addAttribute("categories", categories);
        model.addAttribute("seller", seller);
        return "/productDetail"; // 返回用户详情视图
    }

    // 商品详情查看
    @GetMapping("/order/detail")
    public String getOrderDetail(@RequestParam("id") Integer orderId, Model model) {
        Order order = adminService.getOrderById(orderId);
        Product product = adminService.getProductById(order.getProductId());
        User buyer = adminService.getUserById(order.getBuyerId());
        User seller = adminService.getUserById(order.getSellerId());
        List<Category> categories = adminService.getAllCategories();

        if (order == null) {
            throw new ResourceNotFoundException("订单不存在");
        } else if (product == null) {
            throw new ResourceNotFoundException("商品不存在");
        } else if (buyer == null) {
            throw new ResourceNotFoundException("买家不存在");
        } else if (seller == null) {
            throw new ResourceNotFoundException("卖家不存在");
        }

        model.addAttribute("order", order);
        model.addAttribute("product", product);
        model.addAttribute("buyer", buyer);
        model.addAttribute("seller", seller);
        model.addAttribute("categories", categories);

        return "/orderDetail";
    }

    @PostMapping("/order/delete")
    @ResponseBody
    public Map<String, Object> deleteOrder(@RequestParam("orderId") Integer orderId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查订单状态是否为已完成(-1)
            Order order = adminService.getOrderById(orderId);
            if (order == null) {
                result.put("success", false);
                result.put("message", "订单不存在");
                return result;
            }

            if (order.getStatus() != -1) {
                result.put("success", false);
                result.put("message", "只能删除已完成的订单");
                return result;
            }

            // 执行删除操作
            adminService.deleteOrder(orderId);

            result.put("success", true);
            result.put("message", "删除成功");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
        }
        return result;
    }
}